<template>
    <div>
        <Card>
            <p slot="title" style="text-align:left;height: 25px;">
                客户信息
                <Icon type="social-vimeo" style="color:orange;" v-if="studentInfoData.studentType=='VIP'"></Icon>
                <Tag  v-if="tagList" v-for="item in tagList" :key="item.id" :color="item.colorName">{{item.name}}</Tag>
                <a v-if="appointTelNo"><Icon type="android-call" color="#19be6b" size="25" @click.native="reCall"></Icon></a>
            </p>
            <!--<div slot="extra">-->
                <!--<resetPwd :data="studentInfoData.familyListData"></resetPwd>-->
                <!--<a target="_blank" class="vipkid-btn" :href="'http://fireman.management.vipkid.com.cn/user/student/student/'+studentId"> 去FM管理端 <Icon type="chevron-right"></Icon></a>-->
                <!--<a target="_blank" class="vipkid-btn" :href="'http://clt.management.vipkid.com.cn/user/student/student/'+studentId"> 去LP管理端 <Icon type="chevron-right"></Icon></a>-->
            <!--</div>-->
            <Row>
                <Col span="16">
                <!--<studentInfo :data="studentInfoData"></studentInfo>-->
                <div v-for="item in workInfo ">
                    <!--<span>电话号码：</span><span>workInfo.dcg_Id</span>-->
                    <!--<span>短信号码：</span><span>workInfo.dcg_Channel</span>-->
                    <!--<span>webcaht号码：</span><span>workInfo.dcg_StartTime</span>-->
                    <!--<span>微信号码：</span><span>workInfo.dcg_ToEmail</span>-->
                    <!--<span>邮件号码：</span><span>workInfo.dcg_customerId</span>-->
                    <!--<span>邮件号码：</span><span>workInfo.dcg_fromEmail</span>-->
                    <!--<span>邮件号码：</span><span>workInfo.dcg_type</span>-->
                    <span>进线号码：</span><span>{{item.dcg_Id}}</span>
                    <span v-show="numshow">关联邮箱:</span><input type="text" v-show="numshow"/>
                    <span v-show="numshow">关联微信号:</span><input type="text" v-show="numshow"/>
                    <button v-show="numshow">确认关联</button>
                </div>

                </Col>
                <Col span="6" offset="2">
                <wordTemplate v-bind:type="'end'"></wordTemplate>
                <remindList :studentObj="studentInfoData"></remindList>
                </Col>
            </Row>
        </Card>

        <Card style="margin-top:20px;position:relative;">
            <Button class="action-btn" id="createSummaryBtn" type="primary" icon="plus-round" @click="createSummary('click',connId,'NORMAL')">新建小结</Button>
            <Button class="go-back-link" type="ghost" icon="chevron-left" @click="goCallConfirmPage"> 返回</Button>
            <Row :gutter="32">
                <Col span="24" class="demo-tabs-style1">
                <Tabs type="card">
                    <TabPane name="callHistory" label="联络历史" id="callHistoryContainer">
                        <callHistory :studentId="studentId" v-on:appendCase="appendCase"></callHistory>
                    </TabPane>
                    <TabPane name="taskHistory" label="工单历史">
                        <taskHistory :studentId="studentId"></taskHistory>
                    </TabPane>
                    <!--<TabPane name="follwup" label="Follow Up">-->
                        <!--<follwUps :studentId="studentId"></follwUps>-->
                    <!--</TabPane>-->
                </Tabs>
                </Col>
            </Row>
        </Card>

    </div>
</template>
<style scoped>
    .action-btn {
        position: absolute;
        top: 12px;
        left: 220px;
        z-index: 100;
    }

    .go-back-link {
        position: absolute;
        right: 20px;
        top: 12px;
        z-index: 100;
    }

    .vipkid-btn {
        display: inline-block;
        border-radius: 4px;
        padding: 6px 15px;
        color: #fff;
        cursor: pointer;
        transition: all .2s linear;
        font-size: 12px;
        user-select: none;
        line-height: 1.5;
        font-weight: 400;
        background: #ff6600;
    }
</style>
<script>
  import {
    mapGetters
  } from 'vuex'
  import studentInfo from 'components/user/studentInfo.vue'
  import resetPwd from 'components/user/resetPwd.vue'
  import callHistory from 'components/voiceCall/callHistory.vue'
  import taskHistory from 'components/voiceCall/taskHistory.vue'
  import createSummaryComponent from './createSummaryComponent'
  import wordTemplate from 'components/voiceCall/wordTemplate.vue'
  import remindList from 'components/voiceCall/remindList.vue'
  import thirdService from 'service/thirdService.js'
  import tagService from 'service/tagService.js'
  import userService from 'service/userService.js'
  import Velocity from 'velocity-animate'
  import domAction from '@/libs/dom.js'
  import follwUps from 'components/user/followUps.vue'
  import appointService from 'service/appointService.js'
  import appendCaseComponent from 'components/voiceCall/appendCase.js'
  import configService from 'service/configService.js'
  import {
    formatDate,
    getAge
  } from '@/libs/filter.js'

  export default {
    name: 'voiceCall',
    data() {
      return {
        connId: '',
        studentId: '',
        createSummaryType: 'click',
        studentInfoData: {},
        userDetailData: [],
        index: 0,
        tagList: [],
        tagColorArr: ['blue', 'green', 'red', 'yellow'],
        appointTelNo: '', //入口  外呼电话
        workInfo:'',
        numshow:false
      }
    },

    computed: {
      ...mapGetters({
        callUserInfo: 'callUserInfo',
        loginUserInfo: 'loginUserInfo',
        cacheExcludeComponent: 'cacheExcludeComponent'
      }),
      workInfoNum(){
        return this.$route.query;
      }

    },
    created() {
      this.$store.dispatch('setCacheExcludeComponentName', [])

      let studentId = this.$route.query.studentId
      if (studentId) {
        this.studentId = studentId
        this.getStudentById(studentId)
        this.getStudentTagList(studentId)

        this.connId = this.callUserInfo.callID
      }

    },
    beforeDestroy() {
      console.log('-----beforeDestroy-----')
      //eventBus.$off('createSummary')

    },
    destroyed() {
      console.log('----destroyed----')
    },
    components: {
      studentInfo,
      resetPwd,
      callHistory,
      taskHistory,
      wordTemplate,
      remindList,
      follwUps
    },
    watch: {
      '$route' (to, from) {
        if (to.path.indexOf('/voicecall') > -1) {
          let studentId = to.query.studentId
          this.studentId = studentId
          this.getStudentById(studentId)
          this.getStudentTagList(studentId)
          this.connId = this.callUserInfo.callID

          let from_param = this.$route.query.from ? this.$route.query.from : ''
          this.from_param = from_param


        }
      },
      async studentInfoData() {
        if (this.cacheExcludeComponent.indexOf('voiceCall') < 0) {
          this.$nextTick(function() {
            //进入来电弹屏详情界面自动带出一个新建小节
            this.createSummary('load', this.connId, "NORMAL")
          })
        }

        //根据connID更新客户信息
        if (this.callUserInfo.callID) {
          try {
            let res = await configService.updateCustomerInfo({
              'connID': this.callUserInfo.callID,
              'customerID': this.studentId,
              'customerName': this.studentInfoData.stuName,
              'userId': this.loginUserInfo.userId

            })
            if (res.result) {
              console.log('成功根据connID更新客户信息')
            }

          } catch (e) {
            console.log(e)
          }

        }
      },
      workInfoNum(){
        this.workInfo = this.$route.query;
      }
    },
    methods: {
      async getStudentById(stuId) {
        let studentObj = await thirdService.getStudentById({
          'id': stuId
        })

        //班主任姓名
        let teacherData = await thirdService.getStaffInfo({
          'id': studentObj.chineseLeadTeacherId
        })
        if (teacherData) {
          studentObj.teacherName = teacherData.name
        }

        //获取学生对应的salesId\tmkid
        let leadData = await thirdService.getStudentLead({
          'id': stuId
        })
        if (leadData) {
          //销售姓名
          if (leadData.salesId) {
            let salesData = await thirdService.getStaffInfo({
              'id': leadData.salesId
            })
            if (salesData) {
              studentObj.salesName = salesData.name
            }

          }
          //tmk姓名
          let tmkData = await thirdService.getStaffInfo({
            'id': leadData.tmkId
          })
          if (tmkData) {
            studentObj.tmkName = tmkData.name
          }

        }

        //学生联系地址
        try {
          let addressData = await thirdService.getStudentAdress({
            'familyId': studentObj.familyId
          })
          studentObj.addressData = addressData
        } catch (e) {
          console.log('获取学生联系地址接口error')
        }


        //获取渠道信息
        try {
          let channeldata = await thirdService.getChannelInfo({
            'id': studentObj.channelId
          })
          studentObj.channelName = channeldata.sourceName
          studentObj.channelInfo = channeldata.channelInfo
        } catch (e) {
          console.log('获取渠道信息接口error')
        }


        //联系人列表
        try {
          let familyListData = await thirdService.getParentsByFamilyIds({
            'familyIds': studentObj.familyId
          })
          studentObj.familyListData = familyListData
        } catch (e) {

          console.log('获取学生联系人列表接口error')
        }



        studentObj.Age = getAge(studentObj.birthday)
        studentObj.createDateTime = formatDate(studentObj.createDateTime, 'yyyy-MM-dd hh:mm:ss')

        studentObj.stuBirthday = formatDate(studentObj.birthday, 'yyyy-MM-dd')

        this.studentInfoData = studentObj
      },

      createSummary(eventtype, connId, type) { //type 为 NORMAL 正常创建小结, type=APPEND  补单
        this.$Message.success('第' + (this.index + 1) + '个小结模版已生成')
        connId = connId ? connId : this.connId
        type = type ? type : "NORMAL"
        if (eventtype === 'click') {
          let tabsDom = document.getElementsByClassName('ivu-tabs-tab')[0];
          tabsDom.click();
          this.createSummaryType = 'click'
        }
        this.createSummaryData = {
          'data': {
            'telNo': this.callUserInfo.telNo,
            'mobileNo': this.callUserInfo.mobileNo,
            'stuId': this.studentId,
            'stuName': this.studentInfoData.name,
            'connId': connId,
            'familyId': this.studentInfoData.familyId,
            'registerDateTime': this.studentInfoData.registerDateTime,
            'birthday': this.studentInfoData.birthday,
            'type': type
          },
          'index': this.index,
          'type': this.createSummaryType
        }

        this.index++;
        //this.$store.dispatch('AddCreateSummaryCount')
        createSummaryComponent.showCreateSummaryComponent(this.createSummaryData)

        userService.saveCustomerInfo(this.studentInfoData)


      },
      async getStudentTagList(studentId) {
        let jsondata = await tagService.getStudentTagList({
          'stuId': studentId
        })
        let vm = this
        if (jsondata.state) {
          let dataList = jsondata.data.tag
          let list = []
          dataList.map(function(item, index) {
            let num = vm.getRandomNum(0, 3)
            item.colorName = vm.tagColorArr[num]
            list.push(item)
          })
          this.tagList = list
        }

      },
      goCallConfirmPage() {
        this.$store.dispatch('setCacheExcludeComponentName', [])
        let updateTagObj = {
          path: '/callConfirm',
          is_nav: true,
          title: '语音客服',
          name: 'callconfirm_index',
          children: []
        }

        this.$store.dispatch('recordDetailPageTags', updateTagObj)
        this.$router.push({
          path: 'callConfirm'
        });
      },
      getRandomNum(min, max) {
        let range = max - min
        let rand = Math.random()
        return (min + Math.round(rand * range))
      },
      //补单
      appendCase(data) {

        let appendCaseData = {
          'data': {
            'telNo': this.callUserInfo.telNo,
            'mobileNo': this.callUserInfo.mobileNo,
            'stuId': this.studentId,
            'stuName': this.studentInfoData.name,
            'connId': data.connId,
            'familyId': this.studentInfoData.familyId,
            'registerDateTime': this.studentInfoData.registerDateTime,
            'birthday': this.studentInfoData.birthday,
            'type': data.type
          },
          'index': this.index,
          'type': 'click'
        }

        appendCaseComponent.showAppendCase(appendCaseData)
        // this.createSummary('click', data.connId, data.type)
      },
      reCall() {
        this.$store.dispatch('fun_reCallNum', this.appointTelNo)
      },
      async getAppointInfo(id) {
        let jsondata = await appointService.getAppointInfo({
          'id': id
        })

        if (jsondata.state) {
          this.appointTelNo = jsondata.data.telNo
        }

      }

    },
    activated() {
      let from_param = this.$route.query.from ? this.$route.query.from : ''
      if (from_param === 'callout') {
        this.createSummaryType = from_param
        this.createSummary('load', this.connId, "NORMAL")
      }


      let appointId = this.$route.query.appointId ? this.$route.query.appointId : ''
      this.getAppointInfo(appointId)


    },
    mounted(){
      console.log(123);
      console.log(this.workInfo );
      this.workInfo = this.$route.query;

      // this.requestWorkList(this.$route.params.nameData);
    },

  }
</script>